var express = require('express');
var router = express.Router();
var userModel = require("../database/model/clineModel")
var bcrypt = require('bcryptjs')
var salt = bcrypt.genSaltSync(10)
    /* GET users listing. */
router.get('/', function(req, res, next) {
    res.send('respond with a resource');
});

router.post('/users', function(req, res, next) {
    console.log(req.body);
    let { username, password } = req.body
    userModel.find({ username }).then(result => {
        console.log(result);
        if (result.length) {
            res.send({
                code: 2,
                msg: '账号已存在'
            })
            return
        }
        var hash = bcrypt.hashSync(password, salt)
        new userModel({ username, password: hash }).save().then(result => {
            res.send({
                code: 1,
                msg: "注册成功"
            })
        })
    })
});
router.get('/users', function(req, res, next) {
    console.log(req);
    let { username, password } = req.query
    userModel.find({ username }).then(result => {
            console.log(req.query);
            console.log(result);
            if (!result.length) {
                res.send({
                    code: 3,
                    msg: "账号不存在，请先注册"
                })
                return
            }
            let hash = result[0].password
            console.log(hash);
            let bool = bcrypt.compareSync(password, hash)
            if (!bool) {
                res.send({
                    code: 4,
                    msg: "密码错误，请重新输入"
                })
                return
            }
            let userinfo = result[0]
            res.send({
                code: 5,
                msg: '登陆成功',
                userinfo
            })
        })
        // let {username,password}=req.body

});
module.exports = router;